package com.example.musicplayerbasedonservice

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.IBinder
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.musicplayerbasedonservice.databinding.ActivityMainBinding
import kotlinx.coroutines.*
import android.Manifest
import android.os.Build
import android.net.Uri
import android.os.Environment
import java.io.File

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var musicService: MusicService? = null
    private var bound = false
    private lateinit var updateSeekBarJob: Job

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as MusicService.MusicBinder
            musicService = binder.getService()
            bound = true
            updateUI()
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            bound = false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_MEDIA_AUDIO)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.READ_MEDIA_AUDIO),
                1
            )
        } else {
            initializeService()
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                    2
                )
            }
        }

        setupClickListeners()
    }

    private fun initializeService() {
        // 添加媒体扫描代码
        val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val contentUri = Uri.fromFile(File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).path))
        mediaScanIntent.data = contentUri
        sendBroadcast(mediaScanIntent)

        // 启动服务
        Intent(this, MusicService::class.java).also { intent ->
            startService(intent)
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    private fun setupClickListeners() {
        binding.playButton.setOnClickListener { musicService?.play() }
        binding.pauseButton.setOnClickListener { musicService?.pause() }
        binding.stopButton.setOnClickListener { musicService?.stop() }
        binding.nextButton.setOnClickListener { musicService?.next() }
        binding.previousButton.setOnClickListener { musicService?.previous() }

        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    musicService?.seekTo(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun updateUI() {
        updateSeekBarJob = CoroutineScope(Dispatchers.Main).launch {
            while (isActive) {
                try {
                    musicService?.let { service ->
                        binding.songTitleTextView.text = service.getCurrentMusicTitle()
                        binding.seekBar.max = service.getDuration()
                        binding.seekBar.progress = service.getCurrentPosition()
                    }
                } catch (e: Exception) {
                    // 记录错误并显示错误消息
                    e.printStackTrace()
                    binding.songTitleTextView.text = "Error: ${e.message}"
                }
                delay(1000)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initializeService()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        updateSeekBarJob.cancel()
        if (bound) {
            unbindService(connection)
            bound = false
        }
    }
}
